<template>
  <div class="table-container">
    <el-table
      :data="tableData"
      border
      style="width: 100%; height: 100%"
      height="100%"
      :header-cell-style="{ textAlign: 'center' }"
      :cell-style="{ textAlign: 'center' }"
    >
      <el-table-column fixed type="index" label="序号" width="50"/>
      <el-table-column fixed label="头像" width="50">
        <template slot-scope="scope">
          <div class="avatar-container">
            <img
              :src="scope.row.avatar || defaultAvatar"
              alt="用户头像"
              class="avatar-img"
            >
          </div>
        </template>
      </el-table-column>
      <el-table-column fixed prop="name" label="姓名"/>
      <el-table-column fixed prop="phone" label="手机号"/>
      <el-table-column label="性别" width="50">
        <template slot-scope="scope">
          <span>{{ genderMap[scope.row.gender] || '未知' }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="grade" label="年级"/>
      <el-table-column prop="region" label="地区"/>
      <el-table-column prop="createTime" label="创建时间"/>
      <el-table-column label="学员端状态">
        <template slot-scope="scope">
          <el-tag :type="scope.row.state === '1' ? 'success' : 'danger'">
            {{ scope.row.state === '0' ? '未开通学员端权限' : '已开通学员端权限' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="剩余课时">
        <template #default="{row}">
          <el-tag :type="row.remainingClassHours == 0 ? 'danger' :row.remainingClassHours > 3 ? 'success' : 'warning'">
            {{ row.remainingClassHours || 0 }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" min-width="200">
        <template #default="{row}">
          <el-button
            type="text"
            :style="{color: themeColor}"
            @click="$emit('on-view', row)"
          >
            详情
          </el-button>
          <el-dropdown trigger="hover" placement="bottom" style="margin-left: 10px">
            <span class="el-dropdown-link">
              <el-button
                type="text"
                :style="{color: themeColor}"
              >
                充值
              </el-button>
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item @click.native="courseRecharge(row)">
                <i class="fa-solid fa-dollar-sign"/><span>充值续费</span>
              </el-dropdown-item>
              <el-dropdown-item @click.native="showRechargeRecord(row)">
                <i class="fa-solid fa-file-waveform"/><span>充值记录</span>
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
          <el-dropdown trigger="hover" placement="bottom" style="margin-left: 10px">
            <span class="el-dropdown-link">
              <el-button
                type="text"
                :style="{color: themeColor}"
              >
                词库
              </el-button>
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item @click.native="openBook(row)">
                <i class="fa-brands fa-openid"/><span>词库开通</span>
              </el-dropdown-item>
              <el-dropdown-item @click.native="openedBook(row)">
                <i class="fa-brands fa-opencart"/><span>已开通词库</span>
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
          <el-dropdown trigger="hover" placement="bottom" style="margin-left: 10px">
            <span class="el-dropdown-link">
              <el-button
                type="text"
                :style="{color: themeColor}"
              >
                学员端
              </el-button>
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item v-if="row.state==='0'" @click.native="grantPermissions(row)">
                <i class="fa-solid fa-hand-spock"/><span>赋予权限</span>
              </el-dropdown-item>
              <el-dropdown-item v-else @click.native="grantPermissions(row)">
                <i class="fa-solid fa-person-circle-xmark"/><span>剥夺权限</span>
              </el-dropdown-item>
              <el-dropdown-item v-if="row.state==='1'" @click.native="getQuickLoginKey(row)">
                <i class="fa-solid fa-key"/><span>速登凭证</span>
              </el-dropdown-item>
              <el-dropdown-item v-if="row.state==='1'" @click.native="resetQuickLoginKey(row)">
                <i class="fa-solid fa-repeat"/><span>重置凭证</span>
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
          <el-dropdown trigger="hover" placement="bottom" style="margin-left: 10px">
            <span class="el-dropdown-link">
              <el-button
                type="text"
                :style="{color: themeColor}"
              >
                更多
              </el-button>
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item @click.native="setAntiForget(row)">
                抗遗忘设置
              </el-dropdown-item>
              <el-dropdown-item @click.native="showClassHistory(row)">
                上课记录
              </el-dropdown-item>
              <el-dropdown-item @click.native="deleteStudent(row)">
                删除学生
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <!-- 课时充值对话框 -->
    <el-dialog
      v-if="courseRechargeDialogVisible"
      title="学生课时充值"
      :visible.sync="courseRechargeDialogVisible"
      width="60%"
      :close-on-click-modal="false"
      center
    >
      <CourseRecharge :student="courseRechargeStudent"/>
    </el-dialog>

    <!-- 词库选择弹框 -->
    <word-library-select-dialog
      v-if="showSelectDialog"
      :visible.sync="showSelectDialog"
      :init-stu-id="courseRechargeStudent.id"
      title="选择要添加的词库"
      @confirm="handleSelectConfirm"
    />

    <!--  已开通词库选择  -->
    <word-library-opened-dialog
      v-if="showOpenedDialog"
      :visible.sync="showOpenedDialog"
      :init-stu-id="courseRechargeStudent.id"
      title="已开通词库"
    />

    <student-class-hour-recharge-record-dialog
      v-if="rechargeRecordDialogVisible"
      :visible.sync="rechargeRecordDialogVisible"
      :student="courseRechargeStudent"
      title="学生课时充值记录查询"
    />

    <class-history-table-dialog
      v-if="classHistoryDialogVisible"
      :visible.sync="classHistoryDialogVisible"
      :student="courseRechargeStudent"
    />

    <set-anti-forget-dialog
      v-if="setAntiForgetDialogVisible"
      :visible.sync="setAntiForgetDialogVisible"
      :student="courseRechargeStudent"
    />

    <!-- 密钥弹框组件 -->
    <key-dialog
      v-if="quickLoginKeyDialogVisible"
      :quick-login-key="quickLoginKey"
      :visible.sync="quickLoginKeyDialogVisible"
    />
  </div>
</template>

<script>
import CourseRecharge from '@/views/student/components/CourseRecharge.vue'
import WordLibrarySelectDialog from '@/views/vocabulary/component/WordLibrarySelectDialog.vue'
import WordLibraryOpenedDialog from '@/views/vocabulary/component/WordLibraryOpenedDialog.vue'
import StudentClassHourRechargeRecordDialog from '@/views/student/components/StudentClassHourRechargeRecord.vue'
import { delStudent, grantPermissions, quickLoginCertificate, resetQuickLoginKey } from '@/api/student'
import ClassHistoryTableDialog from '@/views/student/components/ClassHistoryTableDialog.vue'
import SetAntiForgetDialog from '@/views/student/components/SetAntiForgetDialog.vue'
import KeyDialog from '@/views/student/components/KeyDialog.vue'

export default {
  name: 'StudentTable',
  components: {
    KeyDialog,
    ClassHistoryTableDialog,
    WordLibraryOpenedDialog,
    WordLibrarySelectDialog,
    CourseRecharge,
    SetAntiForgetDialog,
    StudentClassHourRechargeRecordDialog
  },
  props: {
    tableData: {
      type: Array,
      required: true
    },
    genderMap: {
      type: Object,
      required: true
    },
    themeColor: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      courseRechargeDialogVisible: false,
      showSelectDialog: false,
      showOpenedDialog: false,
      courseRechargeStudent: {},
      rechargeRecordDialogVisible: false,
      classHistoryDialogVisible: false,
      setAntiForgetDialogVisible: false,
      quickLoginKeyDialogVisible: false,
      quickLoginKey: ''
    }
  },
  methods: {
    courseRecharge(row) {
      this.courseRechargeDialogVisible = true
      this.courseRechargeStudent = row
    },
    handleSelectConfirm(data) {
      console.log(data)
    },
    openBook(row) {
      this.showSelectDialog = true
      this.courseRechargeStudent = row
    },
    openedBook(row) {
      this.showOpenedDialog = true
      this.courseRechargeStudent = row
    },
    async deleteStudent(row) {
      // 删除确实
      this.$confirm('确定要删除该学生吗？此操作不可逆，并将清空学生有关所有数据。请谨慎！', '确认删除', {
        confirmButtonText: '我已知晓风险，继续删除',
        cancelButtonText: '取消删除',
        type: 'warning'
      }).then(async() => {
        const res = await delStudent({ stuId: row.id })
        this.$notify({ type: 'success', message: '删除成功' })
        this.$emit('on-search')
      }).catch(() => {
        this.$notify.info('已取消删除')
      })
    },
    showRechargeRecord(row) {
      this.courseRechargeStudent = row
      this.rechargeRecordDialogVisible = true
    },
    setAntiForget(row) {
      this.courseRechargeStudent = row
      this.setAntiForgetDialogVisible = true
    },
    showClassHistory(row) {
      this.courseRechargeStudent = row
      this.classHistoryDialogVisible = true
    },
    // 剥夺权限
    async grantPermissions(row) {
      await grantPermissions({ id: row.id })
      this.$emit('reload')
    },
    async getQuickLoginKey(row) {
      this.quickLoginKey = await quickLoginCertificate({ id: row.id })
      this.quickLoginKeyDialogVisible = true
    },
    async resetQuickLoginKey(row) {
      await resetQuickLoginKey({ id: row.id })
      this.quickLoginKey = ''
      this.$notify({ type: 'success', message: '重置成功' })
    }
  }
}
</script>

<style scoped>
.table-container {
  flex: 1;
  overflow-y: auto;
  margin-bottom: 20px;
}

.avatar-container {
  display: flex;
  justify-content: center;
}

.avatar-img {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  object-fit: cover;
  border: 2px solid #e5e6eb;
}

.table-container {
  flex: 1;
  overflow-y: auto; /* 保持纵向滚动 */
  margin-bottom: 20px;
  /* 预留滚动条空间，避免表格内容跳动 */
  padding-right: 4px;
}

/* -------------------------- 滚动条美化（WebKit 内核：Chrome/Safari/Edge） -------------------------- */
/* 1. 隐藏原生滚动条的默认外观 */
.table-container::-webkit-scrollbar {
  width: 8px; /* 滚动条宽度 */
  height: 8px; /* 横向滚动条高度（如果需要） */
}

/* 2. 滚动条轨道（背景） */
.table-container::-webkit-scrollbar-track {
  background: #f1f1f1; /* 轨道底色 */
  border-radius: 4px; /* 轨道圆角 */
}

/* 3. 滚动条滑块（可拖动部分） */
.table-container::-webkit-scrollbar-thumb {
  background: #c0c0c0; /* 滑块默认颜色 */
  border-radius: 4px; /* 滑块圆角 */
  transition: background 0.3s ease; /* hover 过渡效果 */
}

/* 4. 滑块 hover 状态 */
.table-container::-webkit-scrollbar-thumb:hover {
  background: #a0a0a0; /* 滑块 hover 加深颜色 */
}

/* 5. 滚动条边角（轨道与滑块的交汇处） */
.table-container::-webkit-scrollbar-corner {
  background: #f1f1f1;
}

/* -------------------------- 滚动条美化（Firefox 适配） -------------------------- */
.table-container {
  /* Firefox 滚动条宽度 + 轨道样式 */
  scrollbar-width: thin; /* 可选：auto/thin/none */
  scrollbar-color: #c0c0c0 #f1f1f1; /* 滑块颜色 轨道颜色 */
}

/* -------------------------- 表格其他样式（保持不变） -------------------------- */
.avatar-container {
  display: flex;
  justify-content: center;
}

.avatar-img {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  object-fit: cover;
  border: 2px solid #e5e6eb;
}
</style>
